package org.example.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 发送数据的web工具
 * */
public class WebUtil {
    /**
     * 该方法 用于想客户端响应数据
     * */
    public static void  writeJson(HttpServletResponse res,Object jsonObject){
        String json;


        try {
            //将对象转换为json数据
            ObjectMapper mapper =new ObjectMapper();
            json = mapper.writeValueAsString(jsonObject);//对象转化json
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        res.setContentType("application/json;charset=utf-8");
        try {
            res.getWriter().write(json);//发送响应数据
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
